﻿using MySqlConnector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;

namespace YitWeb.Common
{
    public class Db
    {
        public static T Create<T>() where T: Db, new()
        {
            return new T();
        }

        private MySqlConnection GetConnection()
        {
            string strConn = Config.GetString("MySql");
            return new MySqlConnection(strConn);
        }

        public List<T> List<T>(string sql, object param)
        {
            using (var conn = this.GetConnection())
            {
                return conn.Query<T>(sql, param).ToList();
            }
        }

        public PageInfo<T> List<T>(string sql, object param, PageInfo pageInfo)
        {
            string sqlCount = $"SELECT COUNT(*) FROM ({sql}) A";
            string sqlPage = sql + $" LIMIT {pageInfo.PageStart}, {pageInfo.PageSize}";
            using (var conn = this.GetConnection())
            {
                int count = conn.QuerySingle(sqlCount, param); 
                var list = conn.Query<T>(sqlPage, param).ToList();
                return pageInfo.Result(list, count);
            }
        }

        /// <summary>
        /// 插入实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns>int Key value or null </returns>
        public int? Insert<T>(T entity)
        {
            using (var conn = this.GetConnection())
            {
                return conn.Insert(entity);
            }
        }

        public int Update<T>(T entity)
        {
            using (var conn = this.GetConnection())
            {
                return conn.Update(entity);
            }
        }
    }
}
